package com.example.teesystem.common.Permission;

import com.example.teesystem.common.cache.CourseCache;
import com.example.teesystem.common.cache.IssueCache;
import com.example.teesystem.common.cache.UserCache;
import com.example.teesystem.common.exception.CustomException;
import com.example.teesystem.common.utils.PermissionUtil;
import com.example.teesystem.common.utils.ResultCode;
import com.example.teesystem.filter.MyHandlerInterceptor;
import com.example.teesystem.mapper.AssistantMapper;
import com.example.teesystem.mapper.ExamPaperMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.Servlet;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.nio.file.AccessDeniedException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author pxr
 * @data 2022/5/9 16:57
 */
@Component
@RequiredArgsConstructor
public class PermissionInterceptor implements HandlerInterceptor {
    private final AssistantMapper assistantMapper;
    private final ExamPaperMapper examPaperMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler){

        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        //在方法上寻找注解（这里是反射）
        PermissionCheck permission = method.getAnnotation(PermissionCheck.class);

        //ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(httpServletRequest);
        //如果没有添加权限注解则直接跳过允许访问
        if (permission == null) {
            return true;
        }
        Map<String,String[]> map = request.getParameterMap();
//        System.out.println(JSONUtil.parse(map));
//        Parameter[] s = method.getParameters();
//        for(int i = 0; i < s.length;i++){
//            System.out.println(s[i]);
//        }

        Integer courseId = null;
        if(UserCache.userMap.get(MyHandlerInterceptor.getUid()).getType() == 0){
            return true;
        }
        if(map.containsKey("courseId")){
            System.out.println(Integer.parseInt(map.get("courseId")[0]));
            courseId = Integer.parseInt(map.get("courseId")[0]);
        }else {
             if(map.containsKey("issueId")){
                int issueId = Integer.parseInt(map.get("issueId")[0]);
                courseId = IssueCache.issueMap.get(issueId);
            }else if(map.containsKey("paperId")){
                int paperId = Integer.parseInt(map.get("paperId")[0]);
                courseId = examPaperMapper.getCourseIdByPaperId(paperId);
            }else if(map.containsKey("id")){
                courseId = Integer.parseInt("id");
            }
        }


        Long per = null;
        long myPermission = permission.value();

        if(courseId == null){
            throw new CustomException(ResultCode.ASSISTANT_PERMISSION_ERROR);
        }else {
            if(CourseCache.courseMap.get(courseId)!=null) {
                System.out.println(CourseCache.courseMap.get(courseId));
                if(CourseCache.courseMap.get(courseId).getTeacher()==MyHandlerInterceptor.getUid()) {
                    return true;
                }else {
                    per = assistantMapper.getAssistantPermission(MyHandlerInterceptor.getUid(),courseId);
                    if(per == null){
                        throw new CustomException(ResultCode.ASSISTANT_PERMISSION_ERROR);
                    }else {
                        if(PermissionUtil.verify(per,myPermission)) {
                            return true;
                        } else {
                            throw new CustomException(ResultCode.ASSISTANT_PERMISSION_ERROR);
                        }
                    }
                }

            }else {
                throw new CustomException(ResultCode.ASSISTANT_PERMISSION_ERROR);
            }
        }

    }
}
